#__author__ = 'Kerr Wang'

import serial
import time
import struct
import DataAnalyze
from config import * 
import HttpPost
import log

def send_taken(serialPort, mechineCode, num):
	mechine = (0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E)
	Taken = [mechine[mechineCode], mechine[mechineCode], num] 
	try:
		result = HttpPost.httpTimeValidGet(OBJ_HOST, TIMEVLIAD_URL, PORT)
		if result == True:
			serialPort.write(Taken)
			serialPort.flush()
		else:
			print ("未到长跑时间，不发Token")
	except Exception as fe:
		print("断网中，仍然发Token")
		log.log_file_record(fe)
		serialPort.write(Taken)
		serialPort.flush()

def recv1(serialPort):
	data_list = []	
	data_per_num = serialPort.inWaiting()
	data_num = data_per_num
	data_bytes = serialPort.read(data_per_num)

	while data_per_num != 0:		

		time.sleep(0.1)
		data_per_num = serialPort.inWaiting()
		data_num += data_per_num
		data_bytes += serialPort.read(data_per_num)

	data_list = struct.unpack('B'*data_num, data_bytes)
	return data_list

def recv(serialPort):
	data_list = []	
	data_num = 0;

	data_byte = serialPort.read(1)
	data_bytes = data_byte
	data_num += len(data_byte)

	while data_byte!=b'\xfe' and data_byte!=b'':		

		data_byte = serialPort.read(1) 
		data_num += len(data_byte)
		data_bytes += data_byte

	data_list = struct.unpack('B'*data_num, data_bytes)
	return data_list

if __name__ == '__main__':
	t = serial.Serial("COM7", 9600)
	b = t.isOpen()
	print (b)
	send_taken(t, 0, 0x62)
	time.sleep(5)
	data = recv(t)
	print (data)
	if DataAnalyze.data_correct(data, 9):
		print (DataAnalyze.data_analyze(data, 9))
